package com.yuchen.ishop.web.app.interceptor;


import com.yuchen.ishop.entity.Goods;
import com.yuchen.ishop.service.goods.GoodsRestClient;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Jack Q
 *         购物车拦截
 */
public class CartInterceptor implements HandlerInterceptor {

    private final static Logger LOG = Logger.getLogger(CartInterceptor.class);

    @Autowired
    private GoodsRestClient goodsRestClient;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        LOG.debug(request.getServletPath());
        String url = request.getServletPath();

        if (url.startsWith("/cartCookieAjax.htm")) {
            Long id = NumberUtils.toLong(request.getParameter("goodsId")) ;
            if(id <= 0) {
                response.sendRedirect(request.getContextPath() + "/error.htm");
                return false;
            }
            Goods goods = goodsRestClient.get(id);
            if(goods.getState()==2){
                response.sendRedirect(request.getContextPath() + "/error.htm");
                return false;
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }


}
